<template>
  <BasicModal
    v-bind="$attrs"
    :minHeight="400"
    :width="600"
    @register="registerModal"
    :title="
      isUpdate
        ? t('routes.table.departmentManagement.editDepartment')
        : t('routes.table.departmentManagement.addDepartment')
    "
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './dept.data';
  import { useI18n } from '/@/hooks/web/useI18n';

  import { GetOrgsData } from '/@/api/demo/system';

  const { t } = useI18n();

  const emit = defineEmits(['success', 'register']);

  const isUpdate = ref(false);
  const OrgId = ref('');

  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      closeModal();
      emit('success', {
        isUpdate: unref(isUpdate),
        values: { ...values, parentOrgId: OrgId.value },
      });
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 100,
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    OrgId.value = data.parentOrgId;
    updateSchema([
      {
        field: 'id',
        dynamicDisabled: !!unref(isUpdate),
      },
    ]);
    if (unref(isUpdate)) {
      GetOrgsData(OrgId.value).then((res) => {
        setFieldsValue(res);
        OrgId.value = res.parentOrgId;
      });
    }
  });
</script>
